<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div>
    <div style="height: 50px; margin: 5px; text-align: center;">
      <el-input 
        v-model="name" 
        placeholder="角色名称" 
        :suffix-icon="Search" 
        style="width: 200px"
        @keyup.enter="loadPost"
      />
      
      <el-select 
        v-model="register" 
        filterable 
        placeholder="是否可注册" 
        style="margin-left: 5px;width: 200px"
      >
        <el-option 
          v-for="item in registerData" 
          :key="item.id" 
          :label="item.name" 
          :value="item.id"
        />
      </el-select>
      
      <el-select 
        v-model="status" 
        filterable 
        placeholder="角色状态" 
        style="margin-left: 5px;width: 200px"
      >
        <el-option 
          v-for="item in statusData" 
          :key="item.id" 
          :label="item.name" 
          :value="item.id"
        />
      </el-select>

      <el-button 
        type="success" 
        :icon="Search" 
        circle 
        style="margin-left: 5px;" 
        @click="loadPost()"
      />

      <el-button 
        type="primary" 
        :icon="Refresh" 
        circle 
        style="margin-left: 5px;"
        @click="resetParam()"
      />

      <el-button 
        type="primary" 
        :icon="Plus" 
        circle 
        style="margin-left: 5px;" 
        @click="add()"
      />
      
      <el-button 
        type="danger" 
        :icon="Delete" 
        circle 
        style="margin-left: 5px;" 
        @click="delHandle(null)"
        :disabled="delBtnStatus"
      />
    </div>
    
    <el-table 
      ref="multipleTableRef" 
      :data="tableData" 
      tooltip-effect="dark" 
      style="width: 100%" 
      border 
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column prop="name" label="名称" width="120" />
      
      <el-table-column prop="code" label="编码" width="120" />

      <el-table-column prop="remark" label="描述" show-overflow-tooltip />

      <el-table-column prop="register" label="是否可注册" width="100">
        <template #default="scope">
          <el-switch 
            :model-value="scope.row.register === 1" 
            style="margin-right: 20px"
            @change="modRegisterStatus(scope.row.id)"
          />
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="是否可用" width="150">
        <template #default="scope">
          <el-switch 
            :model-value="scope.row.status == 1" 
            active-color="#13ce66" 
            inactive-color="#ff4949" 
            active-text="正常"
            inactive-text="禁用" 
            @change="modStatus(scope.row.id)"
          />
        </template>
      </el-table-column>

      <el-table-column 
        prop="createTime" 
        width="200" 
        label="创建时间" 
        :formatter="formatDate"
      />

      <el-table-column prop="icon" label="操作" fixed="right" width="400">
        <template #default="scope">
          <el-button type="text" @click="permHandle(scope.row.id)">分配权限</el-button>
          
          <el-button 
            type="primary" 
            :icon="Edit" 
            circle 
            @click="mod(scope.row)"
            style="margin-left: 5px;"
          />
          
          <el-button 
            type="danger" 
            :icon="Delete" 
            circle 
            style="margin-left: 5px;"
            @click="delHandle(scope.row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="pageNum"
      :page-sizes="[5, 10, 20, 30]" 
      :page-size="pageSize" 
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />
    
    <el-dialog 
      v-model="centerDialogVisible" 
      title="角色表单" 
      width="800px" 
      center
    >
      <el-form 
        ref="formRef" 
        :rules="rules" 
        :model="form" 
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" style="width: 600px;" />
        </el-form-item>
        
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" style="width: 600px;" />
        </el-form-item>
        
        <el-form-item label="角色描述" prop="remark">
          <el-input v-model="form.remark" style="width: 600px;" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
    
    <el-dialog 
      v-model="permDialogVisible" 
      title="分配权限" 
      width="600px"
    >
      <el-form :model="permForm">
        <el-tree 
          :data="TreeData" 
          show-checkbox 
          ref="permTreeRef" 
          :default-expand-all="true" 
          node-key="id"
          :check-strictly="true" 
          :props="defaultProps"
        />
      </el-form>
      
      <template #footer>
        <el-button @click="allSelect()" type="primary">{{ btntext }}</el-button>
        <el-button @click="permDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPermFormHandle('permForm')">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// eslint-disable-next-line vue/multi-word-component-names
import { ref, reactive, onMounted } from 'vue'
import { 
  Search, 
  Refresh, 
  Plus, 
  Delete, 
  Edit 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import api from '@/axios/index'

// refs
const multipleTableRef = ref()
const formRef = ref()
const permTreeRef = ref()

// 数据响应式

// 表格数据
const tableData = ref([])
// 分页配置
const pageSize = ref(10)
const pageNum = ref(1)
const total = ref(0)

const btntext = ref("全选")
const allstatus = ref(false)
// 条件搜索
const name = ref("")
const register = ref("")
const status = ref(1)

const statusData = [
  { id: 1, name: "正常" },
  { id: 0, name: "禁用" }
]

const registerData = [
  { id: 1, name: "是" },
  { id: 0, name: "否" }
]

// 多选删除
const multipleSelection = ref([])
// 增改表单
const centerDialogVisible = ref(false)
const permDialogVisible = ref(false)
const delBtnStatus = ref(true)

const form = reactive({
  id: "",
  name: "",
  code: "",
  remark: ""
})

const rules = {
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入角色编码", trigger: "blur" }]
}

// 权限树数据
const TreeData = ref([])
const IdsData = ref([])
const defaultProps = {
  children: "children",
  label: "name"
}

// 权限分配表单
const permForm = reactive({})

// 方法
// 格式化时间显示
const formatDate = (row, column) => {
  let data = row[column.property]
  if (data == null) {
    return null
  }
  let dt = new Date(data)
  return (
    dt.getFullYear() +
    "-" +
    (dt.getMonth() + 1) +
    "-" +
    dt.getDate() +
    " " +
    dt.getHours() +
    ":" +
    dt.getMinutes() +
    ":" +
    dt.getSeconds()
  )
}

const modRegisterStatus = (id) => {
  api.post("/role/modRegisterStatus/" + id)
    
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        loadPost()
      } else {
        ElMessage({
          message: "操作失败！",
          type: "error"
        })
      }
    })
}

const modStatus = (id) => {
  api.post("/role/modStatus/" + id)
    
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        loadPost()
      } else {
        ElMessage({
          message: "操作失败！",
          type: "error"
        })
      }
    })
}

const getMenuTree = () => {
  api.get("/menu/tree").then((res) => {
    TreeData.value = res.data
  })
}

const getMenuIds = () => {
  api.get("/menu/ids").then((res) => {
    IdsData.value = res.data
  })
}

// 重置条件搜索框
const resetParam = () => {
  name.value = ""
  register.value = ""
  status.value = 1
}

const resetForm = () => {
  Object.assign(form, {
    id: "",
    name: "",
    code: "",
    remark: ""
  })
}

const loadPost = () => {
  api.post("/role/listPage", {
    pageSize: pageSize.value,
    pageNum: pageNum.value,
    param: {
      name: name.value,
      status: status.value + "",
      register: register.value + ""
    }
  }).then((res) => {
    console.log(res)
    tableData.value = res.data
    total.value = res.total
  })
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
  delBtnStatus.value = val.length == 0
}

const delHandle = (id) => {
  var ids = []
  if (id) {
    ids.push(id)
  } else {
    multipleSelection.value.forEach((row) => {
      ids.push(row.id)
    })
  }
  api.post("/role/deleteBatch", ids).then((res) => {
    console.log(res)
    ElMessage({
      showClose: true,
      message: "恭喜你，操作成功",
      type: "success"
    })
    loadPost()
  })
}

const add = () => {
  centerDialogVisible.value = true
  resetForm()
}

const mod = (row) => {
  api.get('/role/info/' + row.id).then((res) => {
    Object.assign(form, res.data.role)
  })
  centerDialogVisible.value = true
}

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.id) {
        doMod()
      } else {
        doSave()
      }
    } else {
      ElMessage({
        message: "校验失败",
        type: "error"
      })
    }
  })
}

const doSave = () => {
  api.post("/role/save", form).then((res) => {
    console.log(res)
    if (res.code == 200) {
      // 存储返回的数据
      ElMessage({
        message: "新增成功！",
        type: "success"
      })
      centerDialogVisible.value = false
      loadPost()
      resetForm()
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      })
    }
  })
}

const doMod = () => {
  api.post("/role/update", form).then((res) => {
    console.log(res)
    if (res.code == 200) {
      // 存储返回的数据
      ElMessage({
        message: "修改成功！",
        type: "success"
      })
      centerDialogVisible.value = false
      loadPost()
      resetForm()
    } else {
      ElMessage({
        message: res.msg,
        type: "error"
      })
    }
  })
}

const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`)
  pageSize.value = val
  loadPost()
}

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`)
  pageNum.value = val
  loadPost()
}

const permHandle = (id) => {
  permDialogVisible.value = true
  api.get("/role/info/" + id).then((res) => {
    console.log(res.data)
    permTreeRef.value.setCheckedKeys(res.data.menuIds)
    Object.assign(permForm, res.data.role)
    btntext.value = "全选"
    allstatus.value = false
  })
}

const allSelect = () => {
  if (!allstatus.value) {
    console.log(IdsData.value)
    permTreeRef.value.setCheckedKeys(IdsData.value)
    btntext.value = "取消全选"
    allstatus.value = true
  } else {
    permTreeRef.value.setCheckedKeys([])
    btntext.value = "全选"
    allstatus.value = false
  }
}

const submitPermFormHandle = () => {
  var menuIds = permTreeRef.value.getCheckedKeys()
  api.post("/role/perm/" + permForm.id + "/" + menuIds)
    .then((res) => {
      console.log(res)
      ElMessage({
        showClose: true,
        message: "恭喜你，操作成功",
        type: "success"
      })
      loadPost()
      permDialogVisible.value = false
    })
}

// 生命周期
onMounted(() => {
  loadPost()
  getMenuTree()
  getMenuIds()
})
</script>

<style scoped>
.el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>